#include "server.h"

//////////////////////////////////////////////////////////////////
/// 一些辅助函数
//////////////////////////////////////////////////////////////////

//生成默认的userinfo对象
static xchat::UserInfo makeUserInfo(int index, const QByteArray& avatarData)
{
    xchat::UserInfo userInfo;
    userInfo.setUserId(QString::number(1000 + index));
    userInfo.setNickname("Xiang" + QString::number(index));
    userInfo.setDescription("This is a default user.");
    userInfo.setPhone("001241500000");
    userInfo.setAvatar(avatarData);
    return userInfo;
}
//生成一个messageInfo对象 文本消息
static xchat::MessageInfo makeTextMessageInfo(int index, const QString& chatSessionId, const QByteArray& avatar)
{
    xchat::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index, avatar));

    xchat::StringMessageInfo stringMessageInfo;
    stringMessageInfo.setContent("这是一条消息内容" + QString::number(index));

    xchat::MessageContent messageContent;
    messageContent.setMessageType(xchat::MessageTypeGadget::MessageType::STRING);
    messageContent.setStringMessage(stringMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}
//生成一个messageInfo对象 图片消息
xchat::MessageInfo makeImageMessageInfo(int index, const QString& chatSessionId, const QByteArray& avatar)
{
    xchat::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index, avatar));

    xchat::ImageMessageInfo imageMessageInfo;
    imageMessageInfo.setFileId("testImage");
    // 真实服务器推送的消息数据里, 本身也就不带图片的正文. 只是 fileId.
    // 需要通过 fileId, 二次发起请求, 通过 getSingleFile 接口来获取到内容.
    // imageMessageInfo.setImageContent();

    xchat::MessageContent messageContent;
    messageContent.setMessageType(xchat::MessageTypeGadget::MessageType::IMAGE);
    messageContent.setImageMessage(imageMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}
xchat::MessageInfo makeFileMessageInfo(int index, const QString& chatSessionId, const QByteArray& avatar) {
    xchat::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index, avatar));

    xchat::FileMessageInfo fileMessageInfo;
    fileMessageInfo.setFileId("testFile");
    // 真实服务器推送的消息数据里, 本身也就不带图片的正文. 只是 fileId.
    // 需要通过 fileId, 二次发起请求, 通过 getSingleFile 接口来获取到内容.
    fileMessageInfo.setFileName("test.txt");
    // 此处文件大小, 无法设置. 由于 fileSize 属性, 不是 optional , 此处先设置一个 0 进来
    fileMessageInfo.setFileSize(0);

    xchat::MessageContent messageContent;
    messageContent.setMessageType(xchat::MessageTypeGadget::MessageType::FILE);
    messageContent.setFileMessage(fileMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

xchat::MessageInfo makeSpeechMessageInfo(int index, const QString& chatSessionId, const QByteArray& avatar) {
    xchat::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index, avatar));

    xchat::SpeechMessageInfo speechMessageInfo;
    // 真实服务器推送的消息数据里, 本身也就不带图片的正文. 只是 fileId.
    // 需要通过 fileId, 二次发起请求, 通过 getSingleFile 接口来获取到内容.
    speechMessageInfo.setFileId("testSpeech");

    xchat::MessageContent messageContent;
    messageContent.setMessageType(xchat::MessageTypeGadget::MessageType::SPEECH);
    messageContent.setSpeechMessage(speechMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}
//////////////////////////////////////////////////////////////////
/// HTTP 服务器
//////////////////////////////////////////////////////////////////
HttpServer* HttpServer::instance = nullptr;

HttpServer *HttpServer::getInstance()
{
    if (instance == nullptr) {
        instance = new HttpServer();
    }
    return instance;
}

bool HttpServer::init()
{
    // 返回的值是 int, 表示成功绑定的端口号的数值.
    int ret = httpServer.listen(QHostAddress::Any, 8000);
    if (ret == -1) {
        // 绑定失败!
        qDebug() << "HTTP 服务器绑定端口失败!";
        return false;
    }
    // 路由注册 text->函数
    httpServer.route("/ping", [](const QHttpServerRequest &request)
    {
        (void) request;
        qDebug() << "[http] 收到 ping 请求!";
        QHttpServerResponse response("pong");
        return response;
    });
    //getuserinfo
    httpServer.route("/service/user/get_user_info", [=](const QHttpServerRequest &request)
    {
        return this->getUserInfo(request);
    });
    //getfriendlist
    httpServer.route("/service/friend/get_friend_list", [=](const QHttpServerRequest &request)
    {
        return this->getFriendList(request);
    });
    //getchatsessionlist
    httpServer.route("/service/friend/get_chat_session_list", [=](const QHttpServerRequest &request)
    {
        return this->getChatSessionList(request);
    });
    //getpendingfriendeventlist
    httpServer.route("/service/friend/get_pending_friend_events", [=](const QHttpServerRequest &request)
    {
        return this->getPendingFriendEventList(request);
    });
    //getrecentmsglist
    httpServer.route("/service/message_storage/get_recent", [=](const QHttpServerRequest &request)
    {
        return this->getRecentMessageList(request);
    });
    //transmite_message
    httpServer.route("/service/message_transmit/new_message", [=](const QHttpServerRequest &request)
    {
        return this->newMessage(request);
    });
    //setnickname
    httpServer.route("/service/user/set_nickname", [=](const QHttpServerRequest &request)
    {
        return this->setNickname(request);
    });
    //setdescription
    httpServer.route("/service/user/set_description", [=](const QHttpServerRequest &request)
    {
        return this->setDescription(request);
    });
    //getverifycode
    httpServer.route("/service/user/get_phone_verify_code", [=](const QHttpServerRequest &request)
    {
        return this->getVerifyCode(request);
    });
    //setphonenumber
    httpServer.route("/service/user/set_phone", [=](const QHttpServerRequest &request)
    {
        return this->setPhoneNumber(request);
    });
    //setavatar
    httpServer.route("/service/user/set_avatar", [=](const QHttpServerRequest &request)
    {
        return this->setAvatar(request);
    });
    //removefriend
    httpServer.route("/service/friend/remove_friend", [=](const QHttpServerRequest &request)
    {
        return this->removeFriend(request);
    });
    //addfriend
    httpServer.route("/service/friend/add_friend_apply", [=](const QHttpServerRequest &request)
    {
        return this->addFriend(request);
    });
    //acceptfriendapply
    httpServer.route("/service/friend/add_friend_process", [=](const QHttpServerRequest &request)
    {
        return this->acceptFriendApply(request);
    });
    //creategroupchatsession
    httpServer.route("/service/friend/create_chat_session", [=](const QHttpServerRequest &request)
    {
        return this->createGroupChatSession(request);
    });
    //getgroupchatmemberlist
    httpServer.route("/service/friend/get_chat_session_member", [=](const QHttpServerRequest &request)
    {
        return this->getGroupChatMemberList(request);
    });
    //searchuser
    httpServer.route("/service/friend/search_friend", [=](const QHttpServerRequest &request)
    {
        return this->searchUser(request);
    });
    //searchhistorymessage
    httpServer.route("/service/message_storage/search_history", [=](const QHttpServerRequest &request)
    {
        return this->searchHistoryMessage(request);
    });
    //searchhistorymessagebytime
    httpServer.route("/service/message_storage/get_history", [=](const QHttpServerRequest &request)
    {
        return this->searchHistoryMessageByTime(request);
    });
    //userlogin
    httpServer.route("/service/user/username_login", [=](const QHttpServerRequest &request)
    {
        return this->userLogin(request);
    });
    //userregister
    httpServer.route("/service/user/username_register", [=](const QHttpServerRequest &request)
    {
        return this->userRegister(request);
    });
    //phonelogin
    httpServer.route("/service/user/phone_login", [=](const QHttpServerRequest &request)
    {
        return this->phoneLogin(request);
    });
    //phoneregister
    httpServer.route("/service/user/phone_register", [=](const QHttpServerRequest &request)
    {
        return this->phoneRegister(request);
    });
    //getsinglefile
    httpServer.route("/service/file/get_single_file", [=](const QHttpServerRequest &request)
    {
        return this->getSingleFile(request);
    });
    //speech_to_text
    httpServer.route("/service/speech/speech_recognition", [=](const QHttpServerRequest &request)
    {
        return this->speechToText(request);
    });

    qDebug() << "HTTP 服务器启动成功! 监听端口: " << ret;
    return true;
}

QHttpServerResponse HttpServer::getUserInfo(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetUserInfoReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取用户信息请求失败!";
        xchat::GetUserInfoRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    LOG() << "[REQ 获取用户信息] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    qDebug() << "[http] 收到获取用户信息请求! requestId: " << req.requestId() << " sessionId: " << req.sessionId();
    // 构造响应
    xchat::GetUserInfoRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    xchat::UserInfo userInfo;

    userInfo.setUserId("user123");
    userInfo.setNickname("Alice");
    userInfo.setDescription("Hello, I'm Alice!");
    userInfo.setPhone("1234567890");
    userInfo.setAvatar(loadFileToByteArray(":/resource/image/logo.png"));
    if(userInfo.avatar().isEmpty())
    {
        LOG() << "[RESP 获取用户信息] 用户头像加载失败 使用默认头像!";
    }
    resp.setUserInfo(userInfo);

    QByteArray respBody = resp.serialize(&serializer);

    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");

    return rsp;

}

QHttpServerResponse HttpServer::getFriendList(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetFriendListReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取好友列表请求失败!";
        xchat::GetFriendListRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取好友列表] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    xchat::GetFriendListRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些好友信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 15; ++i) {
        xchat::UserInfo friendInfo = makeUserInfo(i, defaultAvatar);
        resp.friendList().push_back(friendInfo);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getChatSessionList(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetChatSessionListReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取会话列表请求失败!";
        xchat::GetChatSessionListRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取会话列表] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    xchat::GetChatSessionListRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 构造若干个单聊会话
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 20; ++i) {
        xchat::ChatSessionInfo chatSessionInfo;
        chatSessionInfo.setChatSessionId(QString::number(2000 + i));
        chatSessionInfo.setChatSessionName("会话" + QString::number(i) + " <=> " + "Xiang" + QString::number(i));
        chatSessionInfo.setSingleChatFriendId(QString::number(1000 + i));
        chatSessionInfo.setAvatar(defaultAvatar);
        xchat::MessageInfo messageInfo = makeTextMessageInfo(i, chatSessionInfo.chatSessionId(), defaultAvatar);

        chatSessionInfo.setPrevMessage(messageInfo);

        resp.chatSessionInfoList().push_back(chatSessionInfo);
    }
    QByteArray groupAvatar = loadFileToByteArray(":/resource/image/groupAvatar.png");
    //构造一个群聊会话
    {
        xchat::ChatSessionInfo chatSessionInfo;
        chatSessionInfo.setChatSessionId(QString::number(1999));
        chatSessionInfo.setChatSessionName("Xiang群聊");
        chatSessionInfo.setSingleChatFriendId("");
        chatSessionInfo.setAvatar(groupAvatar);
        xchat::MessageInfo messageInfo = makeTextMessageInfo(1999, chatSessionInfo.chatSessionId(), groupAvatar);

        chatSessionInfo.setPrevMessage(messageInfo);

        resp.chatSessionInfoList().push_front(chatSessionInfo);
    }

    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getPendingFriendEventList(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetPendingFriendEventListReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取好友申请列表请求失败!";
        xchat::GetPendingFriendEventListRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取好友申请列表] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    xchat::GetPendingFriendEventListRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些好友申请信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 10; ++i) {
        xchat::FriendEvent friendEvent;
        friendEvent.setSender(makeUserInfo(i, defaultAvatar));
        resp.event().push_back(friendEvent);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getRecentMessageList(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetRecentMsgReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取最近消息列表请求失败!";
        xchat::GetRecentMsgRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取最近消息列表] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " chatSessionID = " << req.chatSessionId();
    xchat::GetRecentMsgRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些消息信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    //debug defaultAvatar的关键信息 用于调试

    for (int i = 0; i < 20; ++i)
    {
        xchat::MessageInfo messageInfo = makeTextMessageInfo(i, req.chatSessionId(), defaultAvatar);
        resp.msgList().push_back(messageInfo);
    }
    //制作一个图片消息
    xchat::MessageInfo imageMessageInfo = makeImageMessageInfo(100, req.chatSessionId(), defaultAvatar);
    resp.msgList().push_back(imageMessageInfo);
    //制作一个文件消息
    xchat::MessageInfo fileMessageInfo = makeFileMessageInfo(101, req.chatSessionId(), defaultAvatar);
    resp.msgList().push_back(fileMessageInfo);



    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::newMessage(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::NewMessageReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析发送消息请求失败!";
        xchat::NewMessageRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    if (req.message().messageType() == xchat::MessageTypeGadget::MessageType::STRING) {
        LOG() << "发送的消息内容=" << req.message().stringMessage().content();
    }
    xchat::NewMessageRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setNickname(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::SetUserNicknameReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析修改用户昵称请求失败!";
        xchat::SetUserNicknameRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 修改用户昵称] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " newNickname = " << req.nickname();
    xchat::SetUserNicknameRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setDescription(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::SetUserDescriptionReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析修改用户签名请求失败!";
        xchat::SetUserDescriptionRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 修改用户签名] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " newDescription = " << req.description();
    xchat::SetUserDescriptionRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getVerifyCode(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::PhoneVerifyCodeReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取验证码请求失败!";
        xchat::PhoneVerifyCodeRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取验证码] requestID = " << req.requestId() << " phoneNumber = " << req.phoneNumber();
    xchat::PhoneVerifyCodeRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    resp.setVerifyCodeId("verifycodeId1234");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setPhoneNumber(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::SetUserPhoneNumberReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析修改手机号请求失败!";
        xchat::SetUserPhoneNumberRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 修改手机号] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " newPhoneNumber = " << req.phoneNumber();
    xchat::SetUserPhoneNumberRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setAvatar(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::SetUserAvatarReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析修改头像请求失败!";
        xchat::SetUserAvatarRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 修改头像] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    xchat::SetUserAvatarRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::removeFriend(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::FriendRemoveReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析删除好友请求失败!";
        xchat::FriendRemoveRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 删除好友] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " friendUserID = " << req.peerId();
    xchat::FriendRemoveRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::addFriend(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::FriendAddReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析添加好友请求失败!";
        xchat::FriendAddRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 添加好友] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " friendUserID = " << req.respondentId();
    xchat::FriendAddRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::acceptFriendApply(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::FriendAddProcessReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析接受好友申请请求失败!";
        xchat::FriendAddProcessRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 接受好友申请] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " friendUserID = " << req.applyUserId();
    xchat::FriendAddProcessRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::createGroupChatSession(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::ChatSessionCreateReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析创建群聊请求失败!";
        xchat::ChatSessionCreateRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 创建群聊] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " groupName = " << req.chatSessionName();
    xchat::ChatSessionCreateRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getGroupChatMemberList(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetChatSessionMemberReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取群成员列表请求失败!";
        xchat::GetChatSessionMemberRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取群成员列表] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " chatSessionID = " << req.chatSessionId();
    xchat::GetChatSessionMemberRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些群成员信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 10; ++i) {
        xchat::UserInfo memberInfo = makeUserInfo(i, defaultAvatar);
        resp.memberInfoList().push_back(memberInfo);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchUser(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::FriendSearchReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析搜索用户请求失败!";
        xchat::FriendSearchRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 搜索用户] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " keyword = " << req.searchKey();
    xchat::FriendSearchRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些搜索结果信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 10; ++i) {
        xchat::UserInfo userInfo = makeUserInfo(i, defaultAvatar);
        resp.userInfo().push_back(userInfo);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchHistoryMessage(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::MsgSearchReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析搜索历史消息请求失败!";
        xchat::MsgSearchRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 搜索历史消息] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " chatSessionID = " << req.chatSessionId() << " keyword = " << req.searchKey();
    xchat::MsgSearchRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些搜索结果信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 20; ++i)
    {
        xchat::MessageInfo messageInfo = makeTextMessageInfo(i, req.chatSessionId(), defaultAvatar);
        resp.msgList().push_back(messageInfo);
    }

    //构造图片消息
    xchat::MessageInfo imageMessageInfo = makeImageMessageInfo(100, req.chatSessionId(), defaultAvatar);
    resp.msgList().push_back(imageMessageInfo);

    //构造文件消息
    xchat::MessageInfo fileMessageInfo = makeFileMessageInfo(101, req.chatSessionId(), defaultAvatar);
    resp.msgList().push_back(fileMessageInfo);

    //构造语音消息 构造五个
    for (int i = 0; i < 5; ++i)
    {
        xchat::MessageInfo speechMessageInfo = makeSpeechMessageInfo(200 + i, req.chatSessionId(), defaultAvatar);
        resp.msgList().push_back(speechMessageInfo);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchHistoryMessageByTime(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetHistoryMsgReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析按时间搜索历史消息请求失败!";
        xchat::GetHistoryMsgRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 按时间搜索历史消息] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " chatSessionID = " << req.chatSessionId() << " startTime = " << req.startTime()
          << " endTime = " << req.overTime();
    xchat::GetHistoryMsgRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    // 添加一些搜索结果信息
    QByteArray defaultAvatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 20; ++i)
    {
        xchat::MessageInfo messageInfo = makeTextMessageInfo(i, req.chatSessionId(), defaultAvatar);
        resp.msgList().push_back(messageInfo);
    }
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::userLogin(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::UserLoginReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析用户登录请求失败!";
        xchat::UserLoginRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 用户登录] requestID = " << req.requestId() << " nickname = " << req.nickname();
    xchat::UserLoginRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    resp.setLoginSessionId("10009");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::userRegister(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::UserRegisterReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析用户注册请求失败!";
        xchat::UserRegisterRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 用户注册] requestID = " << req.requestId() << " nickname = " << req.nickname();
    xchat::UserRegisterRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::phoneLogin(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::PhoneLoginReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析手机号登录请求失败!";
        xchat::PhoneLoginRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 手机号登录] requestID = " << req.requestId() << " phoneNumber = " << req.phoneNumber();
    xchat::PhoneLoginRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    resp.setLoginSessionId("10010");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::phoneRegister(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::PhoneRegisterReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析手机号注册请求失败!";
        xchat::PhoneRegisterRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 手机号注册] requestID = " << req.requestId() << " phoneNumber = " << req.phoneNumber();
    xchat::PhoneRegisterRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getSingleFile(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::GetSingleFileReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析获取单个文件请求失败!";
        xchat::GetSingleFileRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 获取单个文件] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId()
          << " fileID = " << req.fileId();
    xchat::GetSingleFileRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");

    xchat::FileDownloadData fileDownloadData;
    //此处后续要能指出三个情况 图片文件 普通文件 语音文件
    if(req.fileId() == "testImage")
    {
        fileDownloadData.setFileContent(loadFileToByteArray(":/resource/image/cross.png"));
    }
    else if(req.fileId() == "testFile")
    {
        fileDownloadData.setFileContent(loadFileToByteArray(":/resource/file/testFile.txt"));
    }
    else if(req.fileId() == "testSpeech")
    {
        fileDownloadData.setFileContent(loadFileToByteArray(":/resource/speech/tmpRecord.pcm"));
    }
    else
    {
        resp.setSuccess(false);
        resp.setErrmsg("不是预期文件类型");
    }
    resp.setSuccess(true);
    resp.setErrmsg("");

    resp.setFileData(fileDownloadData);
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::speechToText(const QHttpServerRequest &request)
{
    // 解析请求 body
    QByteArray body = request.body();
    xchat::SpeechRecognitionReq req;
    bool parseOk = req.deserialize(&serializer, body);
    //debug
    if (!parseOk)
    {
        qDebug() << "[http] 解析语音转文本请求失败!";
        xchat::SpeechRecognitionRsp resp;
        resp.setRequestId("");
        resp.setSuccess(false);
        resp.setErrmsg("请求格式错误!");
        QByteArray respBody = resp.serialize(&serializer);
        return QHttpServerResponse(respBody, QHttpServerResponse::StatusCode::BadRequest);
    }
    // 构造响应
    LOG() << "[REQ 语音转文本] requestID = " << req.requestId() << " loginsessionID = " << req.sessionId();
    xchat::SpeechRecognitionRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    resp.setRecognitionResult("这是一个测试语音转文本的结果。");
    QByteArray respBody = resp.serialize(&serializer);
    QHttpServerResponse rsp(respBody, QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type", "application/protobuf");
    return rsp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Websocket 服务器
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
WebSocketServer* WebSocketServer::instance = nullptr;
WebSocketServer *WebSocketServer::getInstance()
{
    if (instance == nullptr) {
        instance = new WebSocketServer();
    }
    return instance;
}

bool WebSocketServer::init()
{
    // 1. 连接信号槽
    connect(&websocketServer, &QWebSocketServer::newConnection, this, [=]()
    {
        // 连接建立成功之后.
        qDebug() << "[websocket] 连接建立成功!";

        // 获取到用来通信的 socket 对象. nextPendingConnection 类似于 原生 socket 中的 accept
        QWebSocket* socket = websocketServer.nextPendingConnection();

        // 针对这个 socket 对象, 进行剩余信号的处理
        connect(socket, &QWebSocket::disconnected, this, [=]() {
            qDebug() << "[websocket] 连接断开!";
            //connect(this, &WebSocketServer::sendTextResp, this, [=]() this和this链接的对象 socket释放要断开这个
            disconnect(this, &WebSocketServer::sendTextResp, this, nullptr);
            disconnect(this, &WebSocketServer::sendFriendRemove, this, nullptr);
            disconnect(this, &WebSocketServer::sendAddFriendApply, this, nullptr);
            disconnect(this, &WebSocketServer::sendFriendApplyProcess, this, nullptr);
            disconnect(this, &WebSocketServer::sendCreateGroupChatSession, this, nullptr);
            disconnect(this, &WebSocketServer::sendImageResp, this, nullptr);
            disconnect(this, &WebSocketServer::sendFileResp, this, nullptr);
            disconnect(this, &WebSocketServer::sendSpeechResp, this, nullptr);
        });

        connect(socket, &QWebSocket::errorOccurred, this, [=](QAbstractSocket::SocketError error) {
            qDebug() << "[websocket] 连接出错! " << error;
        });

        connect(socket, &QWebSocket::textMessageReceived, this, [=](const QString& message) {
            qDebug() << "[websocket] 收到文本数据! message=" << message;
        });

        connect(socket, &QWebSocket::binaryMessageReceived, this, [=](const QByteArray& byteArray) {
            qDebug() << "[websocket] 收到二进制数据! " << byteArray.length();
        });

        //发送文本消息通知
        connect(this, &WebSocketServer::sendTextResp, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/logo.png");
            xchat::MessageInfo messageInfo = makeTextMessageInfo(this->messageIndex++, "2000", avatar);

            xchat::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送文本消息响应: " << messageInfo.message().stringMessage().content();
        });
        //发送图片消息
        connect(this, &WebSocketServer::sendImageResp, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/logo.png");
            xchat::MessageInfo messageInfo = makeImageMessageInfo(this->messageIndex++, "2000", avatar);

            xchat::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送图片消息响应: " << messageInfo.message().imageMessage().fileId();
        });
        //发送文件消息
        connect(this, &WebSocketServer::sendFileResp, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/logo.png");
            xchat::MessageInfo messageInfo = makeFileMessageInfo(this->messageIndex++, "2000", avatar);

            xchat::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送文件消息响应: " << messageInfo.message().fileMessage().fileId();
        });
        //发送语音消息
        connect(this, &WebSocketServer::sendSpeechResp, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/logo.png");
            xchat::MessageInfo messageInfo = makeSpeechMessageInfo(this->messageIndex++, "2000", avatar);

            xchat::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送语音消息响应: " << messageInfo.message().speechMessage().fileId();
        });
        //发送删除好友通知
        connect(this, &WebSocketServer::sendFriendRemove, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QString removedFriend = QString::number(1000 + removedFriendUserId++);

            xchat::NotifyFriendRemove notifyFriendRemove;
            notifyFriendRemove.setUserId(removedFriend);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::FRIEND_REMOVE_NOTIFY);
            notifyMessage.setFriendRemove(notifyFriendRemove);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送删除好友通知响应: " << removedFriendUserId;
        });
        //发送添加好友申请通知
        connect(this, &WebSocketServer::sendAddFriendApply, this, [=]() {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
            xchat::UserInfo fromUserInfo = makeUserInfo(100 + addFriendApplyUserId++, avatar);

            xchat::NotifyFriendAddApply notifyFriendAddApply;
            notifyFriendAddApply.setUserInfo(fromUserInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::FRIEND_ADD_APPLY_NOTIFY);
            notifyMessage.setFriendAddApply(notifyFriendAddApply);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送添加好友申请通知响应: " << fromUserInfo.userId();
        });
        // 推送好友申请结果
        connect(this, &WebSocketServer::sendFriendApplyProcess, this, [=](bool isAccepted) {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            QByteArray avatar = loadFileToByteArray(":/resource/image/defaultAvatar.png");
            xchat::UserInfo fromUserInfo = makeUserInfo(100 + friendApplyProcessUserId++, avatar);

            xchat::NotifyFriendAddProcess notifyFriendProcessResult;
            notifyFriendProcessResult.setAgree(isAccepted);
            notifyFriendProcessResult.setUserInfo(fromUserInfo);

            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::FRIEND_ADD_PROCESS_NOTIFY);
            notifyMessage.setFriendProcessResult(notifyFriendProcessResult);

            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            // 发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送好友申请处理结果通知响应: " << fromUserInfo.userId() << " isAccepted=" << isAccepted;

        });
        //发送创建群聊成功
        connect(this, &WebSocketServer::sendCreateGroupChatSession, this, [=]()
        {
            qDebug() << "[websocket] 连接成功!";
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "[websocket] socket无效 发送消息失败!";
                return;
            }
            // 构造响应数据
            xchat::ChatSessionInfo chatSessionInfo;
            chatSessionInfo.setChatSessionId(QString::number(1998 - createGroupChatSessionId++));
            chatSessionInfo.setChatSessionName("Xiang家" + QString::number(createGroupChatSessionId));
            chatSessionInfo.setSingleChatFriendId("");

            QByteArray groupAvatar = loadFileToByteArray(":/resource/image/groupAvatar.png");
            chatSessionInfo.setAvatar(groupAvatar);

            xchat::MessageInfo messageInfo = makeTextMessageInfo(createGroupChatSessionId, chatSessionInfo.chatSessionId(), groupAvatar);
            chatSessionInfo.setPrevMessage(messageInfo);

            xchat::NotifyNewChatSession notifyCreateChatSession;
            notifyCreateChatSession.setChatSessionInfo(chatSessionInfo);
            xchat::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(xchat::NotifyTypeGadget::NotifyType::CHAT_SESSION_CREATE_NOTIFY);
            notifyMessage.setNewChatSessionInfo(notifyCreateChatSession);
            // 序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);
            // 发送消息给客户端
            socket->sendBinaryMessage(body);
            LOG() << "发送创建群聊成功通知响应: " << chatSessionInfo.chatSessionId();
        });

    });
    // 2. 绑定端口, 启动服务
    bool ok = websocketServer.listen(QHostAddress::Any, 8001);
    return ok;
}


